package com.base.helper;

import com.alibaba.fastjson.JSONObject;
import com.base.utils.Base64Util;
import com.base.utils.Redis.RedisUtil;
import com.base.utils.SSLSocketClient;
import com.beust.jcommander.internal.Maps;
import com.base.comm.CommUrls;
import lombok.extern.log4j.Log4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import javax.annotation.PostConstruct;
import java.util.Map;

/**
 * @Date: 2020/5/6 10:41
 * @Description: 四川通话Helper
 */
@Log4j
@Component
public class SCHelper {

    @Autowired
    private RedisUtil redisUtil;
    private static SCHelper scHelper;


    @PostConstruct
    public void init() {
        scHelper = this;
        scHelper.redisUtil = this.redisUtil;
    }


    private static String username = "TestCaaS003";
    private static String userPassword = "1qaz#EDC";
    private static String appkey = "Flp21Ndei1lJ8AQa24vzOqLyb1xT";
    private static String platform = "862860487209";

    private static String Web_Url = "https://www.scnlkf.com";

    /**
     * @Date: 2020/5/6 10:46
     * @Description: 获取token的
     */
    private static String SC_GETTOKEN = "/rest/fastlogin/v1.0";
    /**
     *  @Date: 2020/5/6 16:26
     *  @Description: 拨打电话的（测试环境）
     *
     */
    private static String SC_BEGINCALL="/sandbox/rest/httpsessions/click2Call/v2.0";
    /**
     *  @Date: 2020/5/6 16:26
     *  @Description: 拨打电话的（正式环境）
     *
     */
    private static  String SC_BEGINCALL_REAL="/rest/httpsessions/click2Call/v2.0";

    public static String getUserToken() throws Exception {
//        Jedis jedis = new Jedis(CommUrls.REDIS_HOST_48); // 连接到Redis服务器
//        jedis.auth(CommUrls.REDIS_PWD_48);
        String token = null;
        OkHttpClient client = SSLSocketClient.trustAllSslClient(new OkHttpClient());
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = RequestBody.create(mediaType, "");
        Request request = new Request.Builder()
                .url("https://www.scnlkf.com/rest/fastlogin/v1.0?app_key=Flp21Ndei1lJ8AQa24vzOqLyb1xT&username=TestCaaS003")
                .method("POST", body)
                .addHeader("Authorization", "1qaz#EDC")
                .addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
                .build();
        Response response = client.newCall(request).execute();
        JSONObject jsonObject = JSONObject.parseObject(response.body().string());
        if (jsonObject.get("resultcode").equals("0")) {
            token = jsonObject.getString("access_token");
            try {
                scHelper.redisUtil.set("SCToken",token,86400);
//                jedis.set("SCToken",token);
//                jedis.expire("SCToken",86400);
            }catch (Exception e){
                e.printStackTrace();
                log.error("SC token无法插入");
            }
//            finally {
//                jedis.close();
//            }
//            scHelper.redisCacheManager.set("SCToken",token);
//            scHelper.redisCacheManager.expire("SCToken",86400);
            log.warn("获取SCToken成功:"+token);
        }else{
            log.warn("获取SCToken失败:"+response.body().string());
        }
        return token;
    }

    public static String BeginCall(String caller,String call164,String token,String UUID) throws Exception {
        Boolean flag=false;
        OkHttpClient client = SSLSocketClient.trustAllSslClient(new OkHttpClient());
        MediaType mediaType = MediaType.parse("application/json;charset=UTF-8");
        //获取回调通知Base64进行加密
        String callBackUrl= Base64Util.encodeData(CommUrls.THISSERVER_PORT+"call/SCPush");
        //生成JSON字符串，进行拼接回调：
        Map<String,String> maps=Maps.newHashMap();
        maps.put("calleeNbr","+86"+call164);     //被叫号码
        maps.put("callerNbr","+86"+caller);    //主叫号码
        maps.put("userData",UUID);
        maps.put("feeUrl",callBackUrl);
        String content=JSONObject.toJSONString(maps);
        RequestBody body = RequestBody.create(mediaType, content);
        Request request = new Request.Builder()
                .url("https://www.scnlkf.com/rest/httpsessions/click2Call/v2.0?app_key="+appkey+"&access_token="+token)
                .method("POST", body)
                .addHeader("Content-Type", "application/json;charset=UTF-8")
                .build();
        Response response = client.newCall(request).execute();
        String resultCode = response.body().string();
        JSONObject jsonObject=JSONObject.parseObject(resultCode);
        if (jsonObject.getString("resultcode").equals("0")){
            flag=true;
            log.warn("拨打电话成功："+caller+":"+call164);
        }else {
            log.warn("拨打电话失败："+caller+":"+call164);
        }
        return resultCode;
    }

    public static String getToken() {
//       Jedis jedis = new Jedis(CommUrls.REDIS_HOST_48); // 连接到Redis服务器
//       jedis.auth(CommUrls.REDIS_PWD_48);
        String token="";
        try{
             token=scHelper.redisUtil.get("SCToken");
            if (token==null||token.equals("")){
                try {
                    token= getUserToken();
                } catch (Exception e) {
                    e.printStackTrace();
                    log.warn("获取SCtoken失败"+e.getMessage());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
        }
//        finally {
//            jedis.close();
//        }
        return token;
    }
}
